package org.gitos.cloud.util;

import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.StringRedisTemplate;

import com.alibaba.fastjson.JSONObject;

public class RedisHelper {
	public static final String USER_FLAG = "user_flag";

	private static StringRedisTemplate stringRedisTemplate;
	private static int expireTime;

	public static int getExpireTime() {
		return expireTime;
	}

	public static void setExpireTime(int expireTime) {
		RedisHelper.expireTime = expireTime;
	}

	public static void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
		RedisHelper.stringRedisTemplate = stringRedisTemplate;
	}

	public static String get(String key) {
		return stringRedisTemplate.opsForValue().get(key);
	}

	public static JSession getJSession(String key) {
		String jsessionJson = stringRedisTemplate.opsForValue().get(key);
		try {
			JSession jsession = JSONObject.parseObject(jsessionJson, JSession.class);
			if (jsession.isInvalidate()) {
				RedisHelper.delete(jsession.getGlobalSessionId());
				return null;
			} else {
				return jsession;
			}
		} catch (Exception e) {
			return null;
		}
	}

	public static void set(String key, Object value) {
		stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(value));
	}

	public static void setWithDefaultExireTime(String key, Object value) {
		set(key, value, expireTime, TimeUnit.SECONDS);
	}

	public static void set(String key, Object value, long expireTime, TimeUnit timeUnit) {
		System.out.println("========" + JSONObject.toJSONString(value));
		stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(value), expireTime, timeUnit);
	}

	public static void delete(String key) {
		stringRedisTemplate.delete(key);
	}

	public static void expire(String key, long expireTime, TimeUnit timeUnit) {
		stringRedisTemplate.expire(key, expireTime, timeUnit);
	}

	public static void expireDefault(String key) {
		expire(key, expireTime, TimeUnit.SECONDS);
	}

	public static boolean hasKey(String key) {
		return stringRedisTemplate.hasKey(key);
	}

	public static void setJSession(JSession jsession) {
		if (!jsession.isInvalidate()) {
			RedisHelper.setWithDefaultExireTime(jsession.getGlobalSessionId(), JSONObject.toJSONString(jsession));
		} else {
			RedisHelper.delete(jsession.getGlobalSessionId());
		}

	}
}
